import { collect } from '@/ajax/service/collect';
import { memoIsInApp } from '@/utils/helper';
import { pick } from '@/utils/helper';

function isInIos() {
  if (typeof window === 'undefined') return false;
  const ua = pick('navigator.userAgent')(window);
  return /iphone|ipad|ipod/i.test(ua);
}

export default {
  data() {
    return {
      isInApp: memoIsInApp()
    };
  },

  methods: {
    async report(action, value = {}, eventIdentifier = 'click_action') {
      try {
        const browserReport = ({ action, value = {} }) =>
          collect(JSON.stringify({
            data: [
              {
                platform: isInIos ? 2 : 1,
                time: Date.now(),
                event_identifier: 'click_action',
                label: JSON.stringify({ action, ...value, member_id: 0 })
              }
            ]
          }));
        const appReport = (...rest) => this.$bridge.report(...rest);
        const api = this.isInApp ? appReport : browserReport;

        await api({
          action: eventIdentifier,
          value: { action, action_value: JSON.stringify(value) }
        });
      } catch (e) {
        console.error(e);
      }
    }
  }
};
